/*
 * Copyright 2021 Wicrenet, Inc. All rights reserved.
 */
package com.yinshu.teleshield.config.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Date;

/**
 */
public class DateArgumentResolver implements HandlerMethodArgumentResolver {
    private static final Logger logger = LoggerFactory.getLogger(DateArgumentResolver.class);

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz.equals(Date.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String paramName = parameter.getParameterName();
        if (StrUtil.isBlank(paramName)) {
            return null;
        }
        String paramValue = webRequest.getParameter(paramName);
        if (StrUtil.isBlank(paramValue)) {
            return null;
        }
        //如果传的是时间戳
        try {
            if (StrUtil.isNumeric(paramValue)) {
                long timestamp = Long.parseLong(paramValue);
                return new Date(timestamp);
            }
        } catch (NumberFormatException e) {
            logger.error("时间格式化出错:{} -- {}", paramValue, webRequest.toString());
            return null;
        }
        return DateUtil.parse(paramName);
    }

}
